<script>
import {
  getMaterialList,
  getCollectionList,
  addCollection,
  cancleCollection,
  getMaterialMediaId,
  findOneLevelWeCategories
} from '@/api/chat';

import ClipboardJS from "clipboard";
export default {
  components: {},
  props: {
    sideId: {
      type: String,
      default: '',
    },
    // mediaType 0 图片（image）、1 语音（voice）、2 视频（video），3 普通文件(file) 4 文本 5 海报 7 h5 9 web
    mediaType: {
      type: String,
      default: '0',
    },
    userId: {
      type: String,
      default: '',
    },
    keyword: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      refreshing: false,
      loading: false,
      finished: false,
      error: false,
      pageNum: 0,
      pageSize: 10,
      list: [],
      collectList: [],
      mediaTypeObj: {
        '0': '图片',
        '1': '语音',
        '2': '视频',
        '3': '普通文件',
        '4': '文本',
        '5': '海报',
        '7': 'h5',
        '8': '小程序',
        '9': 'web'
      },
      activeKey: 0,
      activeCatetoryList:[],
      topId:0, clipboardin: null
    }
  },
  watch: {
/*    sideId() {
      console.debug('xxxxxxxxxxxxxxxxxxxxxxxxxx')
      this.getList(1)
      this.$set(this,'activeCatetoryList',[{catetoryName:'测试1',catetoryId:1},{catetoryName:'测试2',catetoryId:2}]);
    }*/


  },
  computed: {},
  created() {
//    this.getList(1);
//    this.userId && this.getCollectionList()
    this.getActiveCatetoryList();

  },
  mounted() {
      let that=this;
      that.clipboardin= new ClipboardJS(".copy-btn");
      that.clipboardin.on('success', function(e) {
          if(e.text){
              that.$toast('复制成功');
          }
          e.clearSelection();
      });

      that.clipboardin.on('error', function(e) {
          console.error('Action:', e.action);
          console.error('Trigger:', e.trigger);
      });

  },
  methods: {
     onRefresh(){
         // 清空列表数据
         this.finished=true;
         // 重置分页
         this.pageNum=0;
         this.pageSize=10;
         // 重置列表
         this.list=[];
         this.getList();

     }
    ,getList(flag) {
       this.refreshing = false;
      if(flag==1){
          // 第一页开始
          this.pageNum=1;
          this.list=[];
      }else{
          // 下拉刷新
          this.pageNum++;
      }

      (this.sideId
        ? getMaterialList({
            userId: this.userId,
            sideId: this.sideId,
            mediaType: this.mediaType,
            topId: this.topId,
            pageSize:this.pageSize,
            pageNum:this.pageNum,
            keyword:this.keyword,
          })
        : getCollectionList({ userId: this.userId, pageSize:this.pageSize, pageNum:this.pageNum, keyword:this.keyword })
      )
        .then(({ rows, total }) => {
            this.loading = false;
          // 判断我的列表
          if (!this.sideId) {
            rows.forEach((element) => {
              element.collection = 1
            })
          }

          this.list.push(...rows);
          // 数据全部加载完成
          if (this.list.length >= total) {
            this.finished = true;
          }else {
            this.finished = false;
          }

        })
        .catch(() => {
          this.error = true;
          this.finished = true
          this.loading=false;
        })
    },
    // getCollectionList() {
    //   let data = { userId: this.userId, pageSize: 1000, pageNum: 1 }
    //   getCollectionList(data).then(({ rows, total }) => {
    //     this.collectList = rows.map((d) => d.materialId)
    //   })
    // },
    send(data) {
      console.debug(data);
      this.$toast.loading({
        message: '正在发送...',
        duration: 0,
        forbidClick: true,
      })
      let entry = undefined
      let _this = this
      wx.invoke('getContext', {}, async function(res) {
        if (res.err_msg == 'getContext:ok') {
            /**
             * 返回进入H5页面的入口类型，目前有
             * normal[除以上场景之外进入，例如工作台，聊天会话等]
             * contact_profile[从联系人详情进入]
             * single_chat_tools[从单聊会话的工具栏进入]
             * group_chat_tools[从群聊会话的工具栏进入]
             * chat_attachment[从会话的聊天附件栏进入]
             * single_kf_tools[从微信客服的工具栏进入]
              */
          entry = res.entry
          let mes = {}
          try {
            if (
              !['single_chat_tools', 'group_chat_tools', 'normal','single_kf_tools'].includes(
                entry
              )
            ) {
              // _this.$toast.clear()
              _this.$toast('入口错误：' + entry)
              return
            }

            // mediaType 0 图片（image）、1 语音（voice）、2 视频（video），3 普通文件(file) 4 文本 5 海报 7 h5 9 web
            // msgtype 文本(“text”)，图片(“image”)，视频(“video”)，文件(“file”)，H5(“news”）和小程序(“miniprogram”)

            let msgtype = {
              0: 'image',
              2: 'video',
              3: 'file',
              4: 'text',
              5: 'news',
              7: 'news',
              8: 'miniprogram',
              9: 'news'
            }
            switch (data.mediaType) {
              case '4':
              default:
                mes.text = {
                  content: data.content, //文本内容
                }
                break
              case '0':
              case '2':
              case '3':
                let dataMediaId = {
                  url: data.materialUrl,
                  type: msgtype[data.mediaType],
                  name: data.materialName,
                }
                let resMaterialId = await getMaterialMediaId(dataMediaId)
                if (!resMaterialId.data) {
                  _this.$toast('获取素材id失败')
                  return
                }
                mes[msgtype[data.mediaType]] = {
                  mediaid: resMaterialId.data.media_id, //
                }
                break
              case '5':
                mes.news = {
                  link: data.materialUrl, //H5消息页面url 必填
                  title: data.content, //H5消息标题
                  desc: data.content, //H5消息摘要
                  imgUrl: data.coverUrl, //H5消息封面图片URL
                }
                break
              case '7':
                  mes.news = {
                      link: data.materialUrl, //H5消息页面url 必填
                      title: data.content, //H5消息标题
                      desc: data.content, //H5消息摘要
                      imgUrl: data.coverUrl, //H5消息封面图片URL
                  }
                  break;
              case '8':
                  mes.miniprogram={
                      appid: data.digest,//小程序的appid
                      title: data.materialName, //小程序消息的title
                      imgUrl: data.coverUrl,//小程序消息的封面图。必须带http或者https协议头，否则报错 $apiName$:fail invalid imgUrl
                      page: data.materialUrl, //小程序消息打开后的路径，注意要以.html作为后缀，否则在微信端打开会提示找不到页面
                  }

                  break;
              case '9':
                  mes.news = {
                      link: data.webType==2?data.materialUrl:'http://qwechat.qlongit.cn/#/test?id='+data.materialId, //H5消息页面url 必填
                      title: data.materialName, //H5消息标题
                      desc: data.digest, //H5消息摘要
                      imgUrl: data.coverUrl, //H5消息封面图片URL
                  }
                  break;


              // case '6':
              //   mes.miniprogram = {
              //     appid: 'wx8bd80126147df384', //小程序的appid
              //     title: '_this is title', //小程序消息的title
              //     imgUrl:
              //       'https://search-operate.cdn.bcebos.com/d054b8892a7ab572cb296d62ec7f97b6.png', //小程序消息的封面图。必须带http或者https协议头，否则报错 $apiName$:fail invalid imgUrl
              //     page: '/index/page.html', //小程序消息打开后的路径，注意要以.html作为后缀，否则在微信端打开会提示找不到页面
              //   }
              //   break
            }
            mes.msgtype = msgtype[data.mediaType]
            // _this.$dialog({ message: 'mes：' + JSON.stringify(mes) })
          } catch (err) {
            _this.$dialog({ message: 'err' + JSON.stringify(err) })
          }
          wx.invoke('sendChatMessage', mes, function(resSend) {
            if (resSend.err_msg == 'sendChatMessage:ok') {
              //发送成功 sdk会自动弹出成功提示，无需再加
              // _this.$toast('发送成功')
            } else {
              //错误处理
              // _this.$dialog({ message: '发送失败：' + JSON.stringify(resSend) })
            }
          })
          _this.$toast.clear()
        } else {
          _this.$toast.clear()
          //错误处理
          _this.$dialog({ message: '进入失败：' + JSON.stringify(res) })
        }
      })
    },
    collect(data) {
      // collection 是否收藏 0未收藏 1 已收藏
      ;(data.collection == 1 ? cancleCollection : addCollection)({
        userId: this.userId,
        materialId: data.materialId,
      }).then(() => {
        data.collection = [1, 0][data.collection]
        this.$toast('操作成功')
      })
    },
    // 获取当前页签下的分类列表，只查询1级分类，也就是parent_id=0的
    getActiveCatetoryList(){
        findOneLevelWeCategories({mediaType:this.mediaType}).then(
            (res)=>{
                console.debug(res);
//                this.$set(this,'activeCatetoryList',[{catetoryName:'测试1',catetoryId:1},{catetoryName:'测试2',catetoryId:2}]);
                this.$set(this,'activeCatetoryList',res.data);
            }
        ).catch(
            (err)=>{

            }
        );

    }
    ,
    // 点击分类，查询对应分类下的素材
    onChange(index){
//        console.debug(this.activeCatetoryList[index-1]);
        // 发起后端请求渲染分类 , 多增加了个全部
        if(index!==0){
            this.topId=this.activeCatetoryList[index-1].topId;
        }else {
            this.topId=0;
        }

        this.onRefresh();
    },
    destroyed(){
        this.clipboardin.destroy();
    }

  },
}
</script>

<template>
  <div>
    <van-row type="flex">
      <van-col span="6">
        <van-sidebar v-if="!!sideId" v-model="activeKey" @change="onChange">

<!--          <van-sidebar-item title="标签名称" dot />
          <van-sidebar-item title="标签名称" info="5" />
          <van-sidebar-item title="标签名称" info="99+" />-->
          <van-sidebar-item title="全部"/>
          <van-sidebar-item v-for="(item,index) in activeCatetoryList" class="list" :key="index" :title="item.name">

          </van-sidebar-item>

        </van-sidebar>
      </van-col>
      <van-col span="18">
        <van-pull-refresh
                v-model="refreshing"
                success-text="刷新成功"
                @refresh="onRefresh"
        >
          <van-list
                  v-model="loading"
                  :finished="finished"
                  finished-text="没有更多了"
                  :error.sync="error"
                  error-text="请求失败，点击重新加载"
                  @load="getList"
          >
            <div v-for="(item, index) in list" class="list" :key="index">
              <div class="content bfc-o">
                <!-- 图片 -->
                <van-image
                        v-if="item.mediaType == 0"
                        width="80"
                        height="80"
                        :src="item.materialUrl"
                />
                <!-- 视频 -->
                <van-image
                        v-if="item.mediaType == 2"
                        width="80"
                        height="80"
                        :src="item.coverUrl"
                />
                <!--海报-->
                <van-image
                        v-if="item.mediaType == 5"
                        width="80"
                        height="80"
                        :src="item.materialUrl"
                />

                <!--web和小程序-->
                <van-image
                        v-if="['8','9'].includes(item.mediaType)"
                        width="80"
                        height="80"
                        :src="item.coverUrl"
                />

                <van-tag type="primary" v-show="['4','9'].includes(item.mediaType)">
                  {{item.digest}}
                </van-tag>

                <!--内容-->
                <div>
                  <!--<textarea rows="10" cols="100" readonly class="title" :id="'content'+item.materialId" :value="['4','7'].includes(item.mediaType) ? item.content : item.materialName" />-->
                  <span class="title" :id="'content'+item.materialId">
                    {{['4','7'].includes(item.mediaType) ? item.content : item.materialName}}
                  </span>
                </div>
              </div>
              <div class="info">
                {{ mediaTypeObj[item.mediaType] }}类型
                <span class="time">{{ item.createTime }}</span>

                <div class="fr flex">
                  <!--<van-button v-show="['4'].includes(item.mediaType)" type="primary" size="mini" class="copy-btn" data-clipboard-action="copy"  :data-clipboard-target="'#content'+item.materialId">复制内容</van-button>-->
                  <van-button v-show="['4'].includes(item.mediaType)" type="primary" size="mini" class="copy-btn" :data-clipboard-text="['4'].includes(item.mediaType) ? item.content : item.materialName">复制内容</van-button>
                  <van-button type="warning" size="mini" class="action" @click="send(item)" >发送</van-button>
                  <van-button v-if="!!userId" class="action" @click="collect(item)" type="info" size="mini">
                    {{ item.collection == 1 ? '取消' : '' }}收藏
                  </van-button>
                </div>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </van-col>
    </van-row>

  </div>
</template>

<style lang="less" scoped>
.content {
  // display: flex;
  .van-image {
    float: left;
    margin: 0 10px 5px 0;
    border: 1px solid #eee;
  }
  .title {
    word-break: break-all;
  }
}
.time {
  margin-left: 5px;
}
</style>
